package com.example.service.impl;

import com.example.entity.SecKillSku;
import com.example.mapper.OrderMapper;
import com.example.mapper.SkuMapper;
import com.example.entity.SecKillOrder;
import com.example.init.InitDataRedis;
import com.example.service.OrderService;
import com.example.vo.SecKillMessageVO;
import jakarta.annotation.Resource;
import java.util.Date;
import java.util.List;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

/**
 * (CommodityOrder)表服务实现类
 *
 * @author 游家纨绔
 * @since 2023-09-05 23:30:00
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {

	@Resource
	private OrderMapper orderMapper;
	@Resource
	private SkuMapper skuMapper;
	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	@Transactional
	public void extracted(SecKillMessageVO secKillMessageVO, SecKillSku sku, String tag) {
		List<SecKillOrder> select = orderMapper.select(SecKillOrder.builder().userId(secKillMessageVO.getUserId()).skuId(secKillMessageVO.getSkuId()).build());
		if (!select.isEmpty()) {
			redisTemplate.opsForValue().set(tag, 123);
			return;
		}
		// 防止库存超卖
		int i = skuMapper.updateStockById(sku.getId());
		// 商品库存自减失败
		if (i < 1) {
			System.out.println(sku.getId() + "号商品自减失败");
			return;
		}
		// 订单创建成功代表秒杀成功
		int insert = orderMapper.insert(
				SecKillOrder.builder()
				            .userId(secKillMessageVO.getUserId())
				            .spuId(secKillMessageVO.getSpuId())
				            .skuId(secKillMessageVO.getSkuId())
				            .gmtCreate(new Date())
				            .gmtModified(new Date())
				            .build()
		);
		// 订单创建失败
		if (insert < 1) {
			System.out.println(secKillMessageVO.getUserId() + "号用户创建" + sku.getId() + "号商品订单失败");
			return;
		}
		// 设置redis抢购过的订单标识，防止重复抢购（秒杀成功了）
		redisTemplate.opsForValue().set(tag, 123);
	}

	@Override
	public SecKillOrder selectByUserIdAndSpuIdAndSkuId(Integer userId, Integer spuId, Integer skuId) {
		Example example = new Example(SecKillOrder.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", userId)
		        .andEqualTo("spuId", spuId)
		        .andEqualTo("skuId", skuId);
		// 订单时间与商品秒杀时间相比，防止商品秒杀前下的订单被误认为是秒杀时创建的
		criteria.andCondition("gmt_create>", InitDataRedis.spikeTime);

		return orderMapper.selectOneByExample(example);
	}

	@Override
	public List<SecKillOrder> selectByUserId(Integer userId) {
		Example example = new Example(SecKillOrder.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", userId);
		List<SecKillOrder> secKillOrders = orderMapper.selectByExample(example);
		return secKillOrders;
	}

}
